package com.woniuxy.controller;

import cn.hutool.json.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.AlipayTradePagePayModel;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.response.AlipayTradePagePayResponse;
import com.alipay.api.response.AlipayTradeWapPayResponse;
import com.woniuxy.entity.Department;
import com.woniuxy.utils.ResponseResult;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/alipay") // /alipay/order
public class AlipayController {

    private final AlipayClient alipayClient;

    // 更新后的密钥配置
    private static final String APP_PRIVATE_KEY = "MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQCtWwC1EB6AM0eEIMYj4UyfMfp19lAz9IPuC+2Ipk8IjCcRpJKd5DkygzbNtsqmGITY6AUn4njCiAM22EBGAX5npzz85vmukj0fAbIXZpJtI9C7O+1a0qdA397gQ5EuYL0GEw0jkZA6uxZSNvA21LSM0LJb7MJPvQ2D1zM7H2lXz9mcAYWp8vpChD8zjmWIe0yrvMec8sX8LPBToTk1k6s9iF8DPlHk1gN0CWCh02g5e8Ak1XiODOkQUOsEADsI9ucM4A5Sod2ZcocdSlzjpjWZsuOwn+4Kz/Swj+FmG45SrsD3Ke3Z63U0l4oUUMVAg7AVGPwFZWD5PVqGuMyOlHd3AgMBAAECggEAJJclwhIB7htkx/3G9MHUU3HQJN/1s9GzmyZHX+WCnxI+GNo83DjU3dWWVrtzcLWSLNpkZDPIO39L9mKUxnIARU6mb9cs8m0Jm6bW+Vt8Iq9BmpOemOIHzYizWXDJjxl6LHMO/ef2on7kyjuwXlJtPZ+7Ve3WYdBMrvxYYu1RZegvFCEmcVZg/pC9eApLX2Coip93kksDfcLj5tcS0ukvMjK7CKJhumRrlpebVqlP6ytfRpj1Fp5YFwLwkIr2VOA64yKDSgdkyi26EslAvlh/+Hmrwj7pMXx1llBS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j5PygkeWaiEVMJDFIjpsmWWQPX481somUaf4flBKST4tRU5FpzG3MmucPY2YZt/2oamimRZsfIkIIo1+m77PJxXaCaL3BvvBRr5KVXyBSntPkk+8CkJd6ieg8Lx61gM4szmZJ8WB7ShBBifPhV1Vs69aHftuuSRP0epNuqkgRKCEx8qB3l4BL0jzexogxBhj2Z+o34lqXwEf4Kq8ybUtxAMcdba8hAjteee3FDNE1nRpuiOREOya1j6hNItqEE3iRRcRVAw9MTUS7DQIDAQAB";
    private static final String APP_ID = "9021000149652915";
    private static final String GATEWAY_URL = "https://openapi-sandbox.dl.alipaydev.com/gateway.do"; // 正式环境
//    private static final String NOTIFY_URL = "http://your-domain.com/alipay/notify"; // 替换为你的实际通知地址
//    private static final String RETURN_URL = "http://localhost:8888/CommunityHealthcare/MakeAppointment"; // 支付完成后的返回地址

    public AlipayController() {
        this.alipayClient = new DefaultAlipayClient(
                GATEWAY_URL,
                APP_ID,
                APP_PRIVATE_KEY,
                "json",
                "UTF-8",
                ALIPAY_PUBLIC_KEY,
                "RSA2"
        );
    }

    @PostMapping("/order")
    public ResponseResult<String> createOrder(@RequestBody Map<String, Object> req) throws AlipayApiException {

        System.out.println("订单传入的参数: " + req);
        Map<String, Object> responseMap = new HashMap<>();

        // 验证必需参数
        if (req.get("TradeNo") == null || req.get("totalAmount") == null ||req.get("subject") == null || req.get("RETURN_URL") == null ||  req.get("NOTIFY_URL") == null ) {
            responseMap.put("error", "缺少必需参数");
            return ResponseResult.fail(500,"缺少必需参数");
        }

        // 构造请求
        AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();
        request.setNotifyUrl(req.get("NOTIFY_URL").toString());
        // 将返回地址通过参数传入
        request.setReturnUrl(req.get("RETURN_URL").toString());

        // 设置业务参数
        AlipayTradePagePayModel model = new AlipayTradePagePayModel();
        model.setOutTradeNo(req.get("TradeNo").toString());
        model.setTotalAmount(req.get("totalAmount").toString());
        model.setSubject(req.get("subject").toString());
        model.setProductCode("FAST_INSTANT_TRADE_PAY");

        // 非必传参数
        if (req.get("body") != null) {
            model.setBody(req.get("body").toString());
        }

        request.setBizModel(model);

        // 调用支付宝接口
        AlipayTradePagePayResponse response = alipayClient.pageExecute(request);
        String form = response.getBody();
        System.out.println("支付宝API响应: " + form);

        if (response.isSuccess()) {
            responseMap.put("form", form);
            System.out.println("调用成功");
        } else {
            responseMap.put("error", "支付宝订单创建失败");
            System.out.println("调用失败");
        }

        return ResponseResult.success(form);
    }

    @GetMapping("/return")
    public String returnUrl(@RequestParam Map<String, String> params) {
        System.out.println("支付宝同步返回参数: " + params);
        // 这里可以处理支付成功后的页面跳转
        return "支付成功，订单号: " + params.get("out_trade_no");
    }

    @PostMapping("/notify")
    public String notifyUrl(@RequestParam Map<String, String> params) {
        System.out.println("支付宝异步通知参数: " + params);
        // 这里处理支付成功的业务逻辑
        // 必须返回success表示成功接收通知
        return "success";
    }
}